/**
 * Created by lmzpc on 2015/10/29.
 */

RED.machine = (function () {

    var models = {};
    var typeToId = {};
    var links = [];

    function getModel(model_name) {
        if (model_name) {
            if (models[model_name])//存在该model
                return models[model_name];
            else {//不存在
                var model = new StateJs.StateMachine(model_name);
                model['states'] = [];
                models[model_name] = model;
                return model;
            }
        } else {
            console.log("model_name not defined!");
        }
    }

    /**
     * @param state_name   状态名称
     */
    function addState(id, state_name) {
        var model = getModel("model");
        var state;
        if (state_name == "initial") {
            state = new StateJs.PseudoState("initial", model, StateJs.PseudoStateKind.Initial);
        } else {
            state = new StateJs.State(state_name, model);
        }
        models['model']['states'].push(state);
        typeToId[id] = state_name;
        return state;
    }


    function getStateName(id) {
        return typeToId[id];
    }

    function addLink(srcId, dstId) {
        links.push({src: srcId, dst: dstId});
    }

    function init() {
        console.log("machine init");
    }

    //生成的代码结果
    function getResult() {
        var result = '';

        for (var m in models) { // 方法
            result += gen(models[m]);
        }

        return result;
    }

    function gen(m) {
        var result = '';
        result += 'var model = new StateJs.StateMachine("model");StateJs.console = console;';
        m['states'].forEach(function (s) {
            if(s.name.indexOf("state")>=0){
                result += 'var ' + s.name + ' = new StateJs.PseudoState("' + s.name + '", model, StateJs.PseudoStateKind.Initial);';
            }else{
                result += 'var ' + s.name + ' = new StateJs.State("' + s.name + '", model);';
            }

        });
        links.forEach(function (l) {
            result += getStateName(l.src) + '.to(' + getStateName(l.dst) + ')';
        });
        return result;
    }

    function run() {
        eval(getResult());
// create a state machine instance
        var instance = new StateJs.StateMachineInstance("instance");

// initialise the model and instance
        StateJs.initialise(model, instance);

// send the machine instance a message for evaluation, this will trigger the transition from stateA to stateB
        StateJs.evaluate(model, instance, "move");
    }

    return {
        init: init,
        getModel: getModel,
        getResult: getResult,
        addState: addState,
        addLink: addLink,
        run:run
    };
})();